package com.iwithlong.service.impl;

import com.imesne.assistant.common.bean.BeanKit;
import com.imesne.assistant.common.exception.ImesneException;
import com.imesne.assistant.common.page.PageList;
import com.imesne.assistant.common.validation.Verifier;
import com.imesne.assistant.jdbc.command.entity.Select;
import com.imesne.assistant.jdbc.command.entity.Update;
import com.imesne.assistant.jdbc.persist.JdbcDao;
import com.iwithlong.entity.*;
import com.iwithlong.enums.EnrollNamelistStatus;
import com.iwithlong.service.ProductSmsService;
import com.iwithlong.service.SmsService;
import com.iwithlong.vo.ActivityEnrollVo;
import com.iwithlong.vo.ProductSmsVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by mhy on 2018/5/31.
 */

@Service
@Transactional
public class ProductSmsServiceImpl implements ProductSmsService {
    @Resource
    private JdbcDao jdbcDao;

    @Resource
    private SmsService smsService;

    @Override
    public ProductSmsVo sendMsgByProduct(Long productId) {
        ProductSmsVo productSmsVo = new ProductSmsVo();
        EnrollProduct enrollProduct = jdbcDao.get(EnrollProduct.class, productId);
        productSmsVo.setActivityEnrollId(enrollProduct.getActivityEnrollId());
        Select<EnrollNamelist> enrollNamelistSelect = jdbcDao.createSelect(EnrollNamelist.class).where("1",1);
        enrollNamelistSelect.and("enrollProductId",productId);
        enrollNamelistSelect.and("status","!=",new Object[]{EnrollNamelistStatus.CANCELLED.getCode()});
        List<EnrollNamelist> enrollNamelists = enrollNamelistSelect.list();
        if(CollectionUtils.isEmpty(enrollNamelists)){
            throw new ImesneException("选择的分组下没有用户报名,无法发送短信");
        }
        StringBuilder enrollNamelistIds = new StringBuilder();
        for (EnrollNamelist enrollNamelist : enrollNamelists) {
            enrollNamelistIds.append(enrollNamelist.getEnrollNamelistId()).append(",");
        }
        enrollNamelistIds.deleteCharAt(enrollNamelistIds.length() - 1);
        productSmsVo.setEnrollNamelistIds(enrollNamelistIds.toString());
        productSmsVo.setQuantity(enrollNamelists.size());
        initProductSmsParams(productSmsVo);
        return productSmsVo;
    }

    private void initProductSmsParams(ProductSmsVo productSmsVo){
        List<String> params = new ArrayList<>();
        ActivityEnroll activityEnroll = jdbcDao.get(ActivityEnroll.class, productSmsVo.getActivityEnrollId());
        Activity activity = jdbcDao.get(Activity.class,activityEnroll.getActivityId());
        params.add(activity.getName());
        params.add(DateFormatUtils.format(activityEnroll.getGmtActivityStart(), "MM月dd日hh:mm"));
        params.add(activityEnroll.getAddress());
        Merchant merchant = jdbcDao.get(Merchant.class,activityEnroll.getMemberId());
        params.add(merchant.getServiceTel());
        productSmsVo.setParams(params);
    }

    @Override
    public void addProductSms(ProductSmsVo productSmsVo) {
        String[] enrollNamelistIds = productSmsVo.getEnrollNamelistIds().split(",");
        ProductSms productSms = BeanKit.convert(new ProductSms(), productSmsVo);
        productSms.setGmtCreate(new Date());
        productSms.setContent(createComment(productSmsVo.getParams()));
        productSms.setStatus(ProductSms.Status.UNAUDIT.getCode());
        ActivityEnroll activityEnroll = jdbcDao.get(ActivityEnroll.class,productSmsVo.getActivityEnrollId());
        Merchant merchant = jdbcDao.get(Merchant.class,activityEnroll.getMemberId());
        productSms.setMemberCode(merchant.getMemberCode());
        Long productSmsId = (Long)jdbcDao.insert(productSms);
        for (String enrollNamelistId : enrollNamelistIds) {
            NamelistSmsRela namelistSmsRela = new NamelistSmsRela();
            namelistSmsRela.setProductSmsId(productSmsId);
            namelistSmsRela.setEnrollNamelistId(Long.valueOf(enrollNamelistId));
            jdbcDao.insert(namelistSmsRela);
        }
    }

    @Override
    public ProductSmsVo sendMsgByEnrollNamelistIds(Long[] enrollNamelistIds) {
        if(enrollNamelistIds.length==0){
            throw new ImesneException("请至少选中一个名单");
        }
        ProductSmsVo productSmsVo = new ProductSmsVo();
        Long enrollNamelistId = enrollNamelistIds[0];
        EnrollNamelist enrollNamelist = jdbcDao.get(EnrollNamelist.class,enrollNamelistId);
        EnrollProduct enrollProduct = jdbcDao.get(EnrollProduct.class, enrollNamelist.getEnrollProductId());
        productSmsVo.setActivityEnrollId(enrollProduct.getActivityEnrollId());
        StringBuilder enrollNamelistIdStrs = new StringBuilder();
        for (Long id : enrollNamelistIds) {
            EnrollNamelist enrollNamelist1 = jdbcDao.get(EnrollNamelist.class,id);
            if(enrollNamelist1.getStatus().equals(EnrollNamelistStatus.CANCELLED.getCode())){
                throw new ImesneException("无法给已经取消报名的用户发送短信");
            }
            enrollNamelistIdStrs.append(id).append(",");
        }
        enrollNamelistIdStrs.deleteCharAt(enrollNamelistIdStrs.length() - 1);
        productSmsVo.setEnrollNamelistIds(enrollNamelistIdStrs.toString());
        productSmsVo.setQuantity(enrollNamelistIds.length);
        initProductSmsParams(productSmsVo);
        return productSmsVo;
    }

    @Override
    public PageList<ProductSmsVo> pageList(ProductSmsVo productSmsVo) {
        Select<ProductSms> productSmsSelect = jdbcDao.createSelect(ProductSms.class).where("1", 1);
        if(StringUtils.isNotBlank(productSmsVo.getMemberCode())){
            productSmsSelect.and("memberCode","like",new Object[]{"%"+productSmsVo.getMemberCode()+"%"});
        }
        if(StringUtils.isNotBlank(productSmsVo.getStatus())){
            productSmsSelect.and("status",productSmsVo.getStatus());
        }
        if(StringUtils.isNotBlank(productSmsVo.getActivityEnrollName())){
            Select<ActivityEnroll> activityEnrollSelect = jdbcDao.createSelect(ActivityEnroll.class).where("1",1);
            activityEnrollSelect.and("title",productSmsVo.getActivityEnrollName());
            ActivityEnroll activityEnroll = activityEnrollSelect.singleResult();
            if(activityEnroll!=null){
                productSmsSelect.and("activityEnrollId",activityEnroll.getActivityEnrollId());
            }else {
                productSmsSelect.and("activityEnrollId","");
            }
        }
        if(StringUtils.isNotBlank(productSmsVo.getMemberCodeEqual())){
            productSmsSelect.and("memberCode",productSmsVo.getMemberCodeEqual());
        }
        productSmsSelect.orderBy("gmtCreate").desc();
        PageList<ProductSms> productSmses = productSmsSelect.pageList(productSmsVo);
        List<ProductSmsVo> productSmsVos = BeanKit.convert(ProductSmsVo.class, productSmses);
        for (ProductSmsVo smsVo : productSmsVos) {
            ActivityEnroll activityEnroll = jdbcDao.get(ActivityEnroll.class,smsVo.getActivityEnrollId());
            smsVo.setActivityEnrollName(activityEnroll.getTitle());
        }
        PageList<ProductSmsVo> result = new PageList<>(productSmsVos,productSmses.getPager());
        return result;
    }

    @Override
    public ProductSmsVo findById(Long productSmsId) {
        ProductSms productSms = jdbcDao.get(ProductSms.class, productSmsId);
        ProductSmsVo productSmsVo = BeanKit.convert(new ProductSmsVo(), productSms);
        List<String> params = Arrays.asList(productSmsVo.getContent().split("&"));
        productSmsVo.setParams(params);
        ActivityEnroll activityEnroll = jdbcDao.get(ActivityEnroll.class,productSmsVo.getActivityEnrollId());
        productSmsVo.setActivityEnrollName(activityEnroll.getTitle());
        return productSmsVo;
    }

    @Override
    public void pass(ProductSmsVo productSmsVo) {
        Update<ProductSms> productSmsUpdate = jdbcDao.createUpdate(ProductSms.class).where("1",1);
        productSmsUpdate.and("productSmsId",productSmsVo.getProductSmsId());
        productSmsUpdate.set("status", ProductSms.Status.AUDIT.getCode());
        productSmsUpdate.execute();
        //发送短信
        Select<NamelistSmsRela> namelistSmsRelaSelect = jdbcDao.createSelect(NamelistSmsRela.class).where("1", 1);
        namelistSmsRelaSelect.and("productSmsId", productSmsVo.getProductSmsId());
        List<NamelistSmsRela> list = namelistSmsRelaSelect.list();
        ArrayList<String> phoneNumbers = new ArrayList<>();
        for (NamelistSmsRela namelistSmsRela : list) {
            EnrollNamelist enrollNamelist = jdbcDao.get(EnrollNamelist.class,namelistSmsRela.getEnrollNamelistId());
            phoneNumbers.add(enrollNamelist.getMobile());
        }
        smsService.sendActivityEnrollMessages(phoneNumbers, productSmsVo.getProductSmsId());
    }

    @Override
    public void notPass(ProductSmsVo productSmsVo) {
        Update<ProductSms> productSmsUpdate = jdbcDao.createUpdate(ProductSms.class).where("1",1);
        productSmsUpdate.and("productSmsId", productSmsVo.getProductSmsId());
        productSmsUpdate.set("status", ProductSms.Status.REFUSED.getCode());
        productSmsUpdate.set("reason", productSmsVo.getReason());
        productSmsUpdate.execute();
    }


    private String createComment(List<String> params) {
        Verifier.init().notBlank(params.get(0), "活动名")
                .notBlank(params.get(1), "活动时间")
                .notBlank(params.get(2), "活动地点")
                .notBlank(params.get(3), "联系号码")
                .notBlank(params.get(4),"备注").validate();
        StringBuilder result =  new StringBuilder();
        for (String param : params) {
            if(param.indexOf("&")!=-1){
                throw new ImesneException("短信内容不能有&特殊符号");
            }
            result.append(param).append("&");
        }
        return result.toString();
    }
}
